package todo;

import done.ClockInput;
import done.ClockOutput;
import se.lth.cs.realtime.semaphore.CountingSem;
import se.lth.cs.realtime.semaphore.MutexSem;
import se.lth.cs.realtime.semaphore.Semaphore;

public class SharedData {
	private long clockTime;
	private long alarmTime;
	
	private Semaphore timeSem;
	private Semaphore alarmSem;
	private Semaphore beepSem;
	
	private int beepCount;
	
	private ClockOutput output;
	private ClockInput input;
	
	
	public SharedData(ClockOutput output, ClockInput input){
		timeSem = new MutexSem();
		alarmSem = new MutexSem();
		beepSem = new MutexSem();
		beepCount = 0;
		this.output = output;
		this.input = input;
	}
	
	public long getClockTime(){
		timeSem.take();
		long returnValue = clockTime;
		timeSem.give();
		return returnValue;
		
	}
	
	public void incClockTime(){
		timeSem.take();
		clockTime = clockTime + 1000;
		timeSem.give();
		int newTime = TimeConverter.convertToInt(getClockTime());
		output.showTime(newTime);
		if (input.getAlarmFlag() && TimeConverter.convertToInt(getAlarmTime()) == TimeConverter.convertToInt(getClockTime())){
			this.startBeep();
		}
		
		if (getBeepCount() > 0){
			output.doAlarm();
		}
		this.decreaseBeepCount();
	}
	
	public void setClockTime(long newClockTime){
		timeSem.take();
		clockTime = newClockTime;
		timeSem.give();
		
	}
	public void setAlarmTime(long newAlarmTime){
		alarmSem.take();
		alarmTime = newAlarmTime;
		alarmSem.give();
		
	}
	
	public long getAlarmTime(){
		alarmSem.take();
		long returnValue = alarmTime;
		alarmSem.give();
		return returnValue;
	}
	
	public int getBeepCount(){
		beepSem.take();
		int beep = this.beepCount;
		beepSem.give();
		return beep;
	}
	
	public void stopBeep(){
		beepSem.take();
		beepCount = 0;
		beepSem.give();
	}
	public void startBeep(){
		beepSem.take();
		beepCount = 20;
		beepSem.give();
	}
	
	public void decreaseBeepCount(){
		beepSem.take();
		beepCount--;
		beepSem.give();
	}

}
